//
//  FolderThumbView.m
//  Documents
//
//  Created by Alex Di Mango 
//  Copyright (c) 2012 Whardoo.com -  All rights reserved.
//

#import "FolderThumbView.h"
#import "NSObject+ThumbViewMaker.h"
#import "DocumentsViewController.h"
#import "DocumentsColors.h"
#import "DocumentsConstants.h"

#define zoomed 0.5
#define CANCEL_TAG 1
#define RENAME_TAG 2


@implementation FolderThumbView
@synthesize folderId,folderImage,folderName,folderRefImage,documentsNumber;
@synthesize swipeButtonR,swipeButtonL;
@synthesize deletingShow,renamingShow;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIButton class]]){
        return NO;
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if(deletingShow){
        [self.swipeButtonR removeFromSuperview];
        [self setDeletingShow:NO];  
    }
    if(renamingShow){
        [self.swipeButtonL removeFromSuperview];
        [self setRenamingShow:NO];  
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    UITouch *touch = [touches anyObject];
    
    DocumentsViewController *home = (DocumentsViewController *)self.superview.superview.nextResponder; 
    [home handleSingleTap:touch];

    [UIView beginAnimations:nil context:self.folderImage]; 
    [UIView setAnimationDuration:0.2]; 
    self.folderImage.transform = CGAffineTransformScale(self.folderImage.transform, 1+zoomed, 1+zoomed);
    self.folderRefImage.transform = CGAffineTransformScale(self.folderRefImage.transform, 1+zoomed, 1+zoomed);
    
    self.folderImage.transform = CGAffineTransformIdentity;
    self.folderRefImage.transform = CGAffineTransformIdentity;
    
    [UIView commitAnimations]; 
    
}

-(void)swipeGestureActionRight:(UILongPressGestureRecognizer *)gesture{
    
    if (self.tag == 1) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"error", @"Documents", nil) message:NSLocalizedStringFromTable(@"cannotDelete", @"Documents", nil) delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
        [alert release];
        
    }else {
    
    [self setDeletingShow:YES];
    swipeButtonR = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // Round button corners
    CALayer *btnLayer = [swipeButtonR layer];
    [btnLayer setMasksToBounds:YES];
    [btnLayer setCornerRadius:5.0f];
    
    [swipeButtonR setTitle:@"Delete" forState:UIControlStateNormal];
    [swipeButtonR setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [swipeButtonR setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    
    
    swipeButtonR.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    swipeButtonR.layer.borderColor = [UIColor blackColor].CGColor;
    swipeButtonR.layer.borderWidth = 0.5f;
    swipeButtonR.layer.cornerRadius = 5.0f;
    swipeButtonR.alpha = 1;
    
    [swipeButtonR addTarget:self action:@selector(deleteItem) forControlEvents:UIControlEventTouchUpInside];

    
    [self addSubview:swipeButtonR];
    [self.superview bringSubviewToFront:swipeButtonR];
    
    
    [UIView animateWithDuration:0.2 delay: 0.0 options: UIViewAnimationOptionTransitionFlipFromTop animations:^{ 
        [swipeButtonR setFrame:CGRectMake(36, 30, 88, 35)]; 
        // Draw a custom gradient
        CAGradientLayer *btnGradient = [CAGradientLayer layer];
        btnGradient.frame = swipeButtonR.bounds;
        btnGradient.colors = [NSArray arrayWithObjects:
                              (id)[DELETE_RED CGColor],
                              (id)[DELETE_RED_GRADIENTE CGColor],
                              nil];
        [swipeButtonR.layer insertSublayer:btnGradient atIndex:0];
    } 
                     completion:^(BOOL finished){ }
     ];
    }    
}

-(void)swipeGestureActionLeft:(UILongPressGestureRecognizer *)gesture{
    
    if (self.tag == 1) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"error", @"Documents", nil) message:NSLocalizedStringFromTable(@"cannotDelete", @"Documents", nil) delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
        [alert release];    
        
    }else {
    
    [self setRenamingShow:YES];
    swipeButtonL = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // Round button corners
    CALayer *btnLayer = [swipeButtonL layer];
    [btnLayer setMasksToBounds:YES];
    [btnLayer setCornerRadius:5.0f];
    
    [swipeButtonL setTitle:@"Rename" forState:UIControlStateNormal];
    [swipeButtonL setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [swipeButtonL setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    
    
    swipeButtonL.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    swipeButtonL.layer.borderColor = [UIColor blackColor].CGColor;
    swipeButtonL.layer.borderWidth = 0.5f;
    swipeButtonL.layer.cornerRadius = 5.0f;
    swipeButtonL.alpha = 1;
    
    [swipeButtonL addTarget:self action:@selector(renameItem) forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:swipeButtonL];
    [self.superview bringSubviewToFront:swipeButtonL];
    
    [UIView animateWithDuration:0.2 delay: 0.0 options: UIViewAnimationCurveLinear animations:^{ 
        [swipeButtonL setFrame:CGRectMake(36, 30, 88, 35)]; 
        // Draw a custom gradient
        CAGradientLayer *btnGradient = [CAGradientLayer layer];
        btnGradient.frame = swipeButtonL.bounds;
        btnGradient.colors = [NSArray arrayWithObjects:
                              (id)[RENAME_GREEN CGColor],
                              (id)[RENAME_GREEN_GRADIENTE CGColor],
                              nil];
    
        [swipeButtonL.layer insertSublayer:btnGradient atIndex:0];
    } 
                     completion:^(BOOL finished){ }
     ];
        
    }
}

-(void)tapGestureAction:(UILongPressGestureRecognizer *)gesture{
  
    DocumentsViewController *home = (DocumentsViewController *)self.superview.superview.nextResponder; 
    [home setSelectedFolder:[MyDocumentsFolder getFolderWithId:[NSNumber numberWithInt:self.tag]]];
    [[home selectedFolder]setCreateDate:[NSDate date]];
    [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_FOLDERS_AND_DOCS object:self];
    
}

-(void)deleteItem
{
    NSLog(@"Delete %@",self.folderName);
    if(deletingShow){
        [self.swipeButtonR removeFromSuperview];
        [self setDeletingShow:NO];  
    }
    self.alpha = 0.5;    
   // self.folderToDelete = [self.folders objectAtIndex:indexPath.row];
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"error", @"Documents", nil) message:NSLocalizedStringFromTable(@"confirmDelete", @"Documents", nil) delegate:self cancelButtonTitle:NSLocalizedStringFromTable(@"cancel", @"Documents", nil) otherButtonTitles:NSLocalizedStringFromTable(@"delete", @"Documents", nil), nil] autorelease];
    [alert setTag:CANCEL_TAG];
    [alert show];    
}
-(void)renameItem
{
    NSLog(@"Rename %@",self.folderName);
    if(renamingShow){
        [self.swipeButtonL removeFromSuperview];
        [self setRenamingShow:NO];  
    }
    self.alpha = 0.5;    
    UIAlertView *msg = [[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"rename", @"Documents", nil) message:NSLocalizedStringFromTable(@"renameMsg", @"Documents", nil) delegate:self
                                       cancelButtonTitle:@"Cancel" otherButtonTitles:@"Rename", nil ];   
    
    [msg setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [msg setTag:RENAME_TAG];
    [msg show];
    [msg release];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    MyDocumentsFolder *myFolder = [MyDocumentsFolder getFolderWithId:[NSNumber numberWithInt:self.tag]];
    DocumentsViewController *home = (DocumentsViewController *)self.superview.superview.nextResponder; 

    //Delete
    if(alertView.tag == CANCEL_TAG && buttonIndex == alertView.firstOtherButtonIndex) 
    {    
        NSArray *docs = [MyDocument getDocumentListForFolderId:[myFolder folderId]];
         for (MyDocument *doc in docs) {
            [MyDocument deleteSelectedDocument:doc];
        }
        [MyDocumentsFolder deleteFolder:myFolder];
        [home setSelectedFolder:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_FOLDERS_AND_DOCS object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_FREE_SPACE object:self];
    }
    //Rename
    else if(alertView.tag == RENAME_TAG && buttonIndex == alertView.firstOtherButtonIndex) 
    {    
        if([MyDocumentsFolder getFolderWithName:[[alertView textFieldAtIndex:0] text] andFolderId:nil]!=nil){
            UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"error", @"Documents", nil) message:[NSString stringWithFormat:@"Il nome “%@” è già stato assegnato. Scegline un altro.",[[alertView textFieldAtIndex:0] text]] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil] autorelease];
            [alert show];
        }
        else {
                [myFolder setName:[[alertView textFieldAtIndex:0] text]];
                [home setSelectedFolder:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_FOLDERS_AND_DOCS object:self];
                [home setSideFolder:myFolder];
             }        
    }else {
        self.alpha = 1.0;
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    if(alertView.tag == RENAME_TAG){
    NSString *inputText = [[alertView textFieldAtIndex:0] text];
    if( [inputText length] >= 1 )
    {
        return YES;
    }
    else
    {
        return NO;
    }
    }        
        return YES;
}

-(void)dealloc{    
    [folderId release];
    [folderImage release];
    [folderRefImage release];
    [folderName release];
    [documentsNumber release];
    [super dealloc];
}



@end
